import React, { Component } from 'react';
import { Layout, Menu } from "antd";
import { connect } from "dva";
import './style.css'
import Router from "../../router/Router";
const {SubMenu, Item} = Menu
const {Sider} = Layout
class SideMenu extends Component {
  constructor(props) {
    super(props);
    this.rootSubmenuKeys = Router.map(item =>item.label)
    this.state = {  
      openKeys:[] 
    }
  }

  keyToTab = key => {
    for (let index = 0; index < Router.length; index++) {
      const child = Router[index];
      for (let index = 0; index < child.children.length; index++) {
        const section = child.children[index];
        if (key === section.key) {
          return section
        }
      }
    }
    return null
  }

  onClick = ({key}) => {
    const tab = this.keyToTab(key)
    if (tab) {
      this.props.dispatch({
        type:'tabs/add',
        payload:tab
      })
    }
  }

  onOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find(
      key => this.state.openKeys.indexOf(key) === -1
    )
    if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys })
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : []
      })
    }
  }

  renderMenu = () => {
    return Router.map(item => (
      <SubMenu key={item.label} title={item.label}>
        {item.children.map(child => (
          <Item key={child.key} >
            {child.label}
          </Item>
        ))}
      </SubMenu>
    ))
  }

  render() {
    return (
      <Sider theme="light">
        <div className="menu-container">
          <Menu
            mode="inline"
            onClick={this.onClick}
            theme="light"
            inlineCollapsed
            openKeys={this.state.openKeys}
            onOpenChange={this.onOpenChange}
          >
            {this.renderMenu()}
          </Menu>
        </div>
      </Sider>
    )
  }
}
export default connect()(SideMenu)